import { View, Text, Button, ScrollView, Image } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import './index.scss'
import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'

interface Questionnaire {
  id: number
  title: string
  description: string
  createdAt: string
  cover?: string // 封面图片 URL
}

// 接口响应类型
interface ApiResponse<T> {
  success: boolean
  data: T
}

export default function Index () {
  useLoad(() => {
    console.log('Home Page loaded.')
  })

  const [list, setList] = useState<Questionnaire[]>([])
  const [loading, setLoading] = useState<boolean>(true)
  const [error, setError] = useState<string | null>(null)

  // 获取问卷列表
  const fetchQuestionnaires = async () => {
    try {
      setLoading(true)
      // const res = await Taro.request<ApiResponse<Questionnaire[]>>({
      //   url: 'https://api.example.com/questionnaires ', // 替换为实际接口
      //   method: 'GET'
      // })
      const res = { "data": { "success": 1, "data": [{"id": 1, "title": "NO1", "description": "description1", "createdAt": "2025-07-08T09:00:00", "cover": ""}] } }

      if (res.data.success) {
        setList(res.data.data)
      } else {
        setError('数据加载失败')
      }
    } catch (err) {
      setError('网络请求失败')
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  // 页面加载时获取数据
  useEffect(() => {
    fetchQuestionnaires()
  }, [])

  // 跳转到答题页
  const handleNavigate = (id: number) => {
    Taro.navigateTo({
      url: `/pages/questionOne/index?questionnaireId=${id}`
    })
  }

  return (
    <View className='home-container'>
      {/* 页面标题 */}
      <View className='header'>
        <Text className='title'>问卷调查</Text>
      </View>

      {/* 加载状态 */}
      {loading && (
        <View className='loading'>
          <Text>加载中...</Text>
        </View>
      )}

      {/* 错误提示 */}
      {error && (
        <View className='error'>
          <Text>{error}</Text>
          <Button onClick={fetchQuestionnaires}>重试</Button>
        </View>
      )}

      {/* 问卷列表 */}
      {!loading && !error && (
        <ScrollView scrollY className='list'>
          {list.map((item) => (
            <View
              key={item.id}
              className='item'
              onClick={() => handleNavigate(item.id)}
            >
              {/* 封面图片 */}
              <Image
                className='cover'
                src={item.cover || require('../../assets/images/default-cover.png')}
              />

              {/* 标题和描述 */}
              <View className='content'>
                <Text className='item-title'>{item.title}</Text>
                <Text className='item-desc'>{item.description}</Text>
                <Text className='item-date'>
                  {new Date(item.createdAt).toLocaleDateString()}
                </Text>
              </View>

              {/* 右侧箭头 */}
              <View className='arrow'>▶</View>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  )
}
